package top.wfzzq.serch;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONArray;

/**
 * Servlet implementation class SerchServlet
 */
@WebServlet("/search.do")
public class SerchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SerchServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// System.out.println("調用了service方法");
		String keyword = req.getParameter("keyword");//jsp部分
		keyword = new String(keyword.getBytes("ISO-8859-1"), "UTF-8");
		System.out.println(keyword);
		// 請求百度搜索引擎
		String content = requestToBaidu("http://www.baidu.com/s?wd=" + keyword);//jsp部分
		// System.out.println(content);
		List<Result> results = parseContent(content);// json
		res.setContentType("text/html;charset=utf-8");
		JSONArray jsonArray=JSONArray.fromObject(results);
		//System.out.println(jsonArray.toString());
		//System.out.println(results.size());
		 res.getWriter().write(jsonArray.toString());

	}

	public List<Result> parseContent(String html) {
		List<Result> results = new ArrayList<Result>();
		// 正則表達式
		// 性能非常卓越
		// 使用起來非常方便
		String regex = "<h3 class=\"t(c-gap-bottom-small)?\">([\\s\\S]*?)</h3>";
		Pattern pat = Pattern.compile(regex);
		Matcher mat = pat.matcher(html);
//		System.out.println(mat.find());//true false
        while(mat.find()) {
//        	System.out.println("============begin===============");
//         	System.out.println(mat.group(1));
        	results.add(new Result(mat.group(2)));
//         	System.out.println("============end===============");
        }
		return results;
	}

	private String requestToBaidu(String url) {
		String html = null;
		// 請求百度搜索引擎
		HttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpGet);
			html = EntityUtils.toString(httpResponse.getEntity());

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return html;
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	// protected void doGet(HttpServletRequest request, HttpServletResponse
	// response)
	// throws ServletException, IOException {
	// // TODO Auto-generated method stub
	// System.out.println("客戶請求Get的ajax");
	// }
	//
	// /**
	// * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	// * response)
	// */
	// protected void doPost(HttpServletRequest request, HttpServletResponse
	// response)
	// throws ServletException, IOException {
	// // TODO Auto-generated method stub
	// // doGet(request, response);
	// super.doPost(request, response);
	// }

}
